import axios from "axios"
import { ThunkAction } from "redux-thunk"
import { RootState } from "../store"

// 正在调用推荐信息api
export const FETCH_RECOMMEND_PRODUCTS_START = 'FETCH_RECOMMEND_PRODUCTS_START'
export const FETCH_RECOMMEND_PRODUCTS_SUCCESS = 'FETCH_RECOMMEND_PRODUCTS_SUCCESS'
export const FETCH_RECOMMEND_PRODUCTS_FAIL = 'FETCH_RECOMMEND_PRODUCTS_FAIL'

interface FetchRecommendProductsStartAction {
  type: typeof FETCH_RECOMMEND_PRODUCTS_START
}

interface FetchRecommendProductsSuccessAction {
  type: typeof FETCH_RECOMMEND_PRODUCTS_SUCCESS,
  payload: any
}

interface FetchRecommendProductsFailAction {
  type: typeof FETCH_RECOMMEND_PRODUCTS_FAIL,
  payload: any
}

export type RecommendProducts = FetchRecommendProductsStartAction | FetchRecommendProductsSuccessAction | FetchRecommendProductsFailAction

export const fetchRecommendProductsStartActionCreator = (): FetchRecommendProductsStartAction => {
  return {
    type: FETCH_RECOMMEND_PRODUCTS_START
  }
}

export const fetchRecommendProductsSuccessActionCreator = (data): FetchRecommendProductsSuccessAction => {
  return {
    type: FETCH_RECOMMEND_PRODUCTS_SUCCESS,
    payload: data
  }
}
export const fetchRecommendProductsFailActionCreator = (error): FetchRecommendProductsFailAction => {
  return {
    type: FETCH_RECOMMEND_PRODUCTS_FAIL,
    payload: error
  }
}


export const giveMeDataActionCreator = ():ThunkAction<void,RootState,unknown,RecommendProducts> => async(dispath,getState) => {
  dispath(fetchRecommendProductsStartActionCreator())
    try {
      const { data } = await axios.get('http://82.157.43.234:8080/api/productCollections', {
        headers: {
          'x-icode':'EDE45279EB142953'
        }
      })
      dispath(fetchRecommendProductsSuccessActionCreator(data))
    } catch (error:any) {
      dispath(fetchRecommendProductsFailActionCreator(error.message))
    }
}